/**
 * @Title: index.js
 * @Description: index 评价任务
 * @author: Fanchao
 * @date: 2020/8/2 11:28 上午
 * @version V1.0
 */

import React, { useEffect, useState } from 'react';
import { Table, Button, Tooltip, message, Input, Select, Modal, Form, DatePicker, Popconfirm } from 'antd';
import { Resizable } from 'react-resizable';
import styles from './index.less';
import SectionTitle from 'components/SectionTitle';
import FilterByKeyWord from 'components/FilterByKeyWord';
import { connect } from 'umi';
import UserModal from '@/pages/evaluations/task/components/UserModal';
import moment from 'moment';
import FinishSampleCountModal from '@/pages/evaluations/task/components/FinishSampleCountModal';
import storageUtils from 'utils/storage';
import {
    cancelEvaluateTask,
    createEvaluateTaskAgain,
    exportTaskUserList,
    getSchoolYearList,
    getTaskEvaluateObjectList,
} from 'api/index';
import * as FileSaver from 'file-saver';
import AddTeacherModal from '@/pages/evaluations/task/components/AddTeacherModal';

const { RangePicker } = DatePicker;

const { Option } = Select;
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
};
const ResizableTitle = props => {
    const { onResize, width, ...restProps } = props;
    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            handle={
                <span
                    className={styles.reactResizableHandle}
                    onClick={e => {
                        e.stopPropagation();
                    }}
                />
            }
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};

const Task = ({ task: { dataSource, keyword, reqPageInfo, modalTitle, modalVisible, finishSampleCountModalVisible, finishSampleCountList, finishStatus, evaluateTaskId }, dispatch, loading }) => {
    const isAdmin = storageUtils.getUser().userRoleTypes.includes('Admin');
    const [evaluateObjectList, setEvaluateObjectList] = useState([]);
    const [evaluateObjectListLoading, setEvaluateObjectListLoading] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [schoolYearListOption, setSchoolYearListOption] = useState([]);

    const [listenCheckCount, setListenCheckCount] = useState(undefined);
    const [schoolYear, setSchoolYear] = useState(undefined);
    const [semester, setSemester] = useState(undefined);
    const [timeType, setTimeType] = useState(undefined);


    const [selectedRows, setSelectedRows] = useState([]);
    const [itemId, setItemId] = useState('');
    const [resetTaskModal, setResetTaskModal] = useState(false);
    const [addModal, setAddModal] = useState(false);

    const fetchEvaluateObjectList = (listenCheckCount, schoolYear, semester, timeType) => {
        setEvaluateObjectListLoading(true);
        getTaskEvaluateObjectList({ listenCheckCount, schoolYear, semester, timeType }).then(res => {
            setEvaluateObjectListLoading(false);
            if (res.status === 'success') {
                const evaluateObjectList = res.result;
                setEvaluateObjectList(evaluateObjectList);
            } else {
                message.error(res.message);
            }
        });
    };

    const getSchoolYearListOption = () => {
        getSchoolYearList().then(res => {
            if (res.status === 'success') {
                const schoolYearListOption = res.result;
                setSchoolYearListOption(schoolYearListOption);
            } else {
                message.error(res.message);
            }
        });
    };

    useEffect(() => {
        fetchEvaluateObjectList(listenCheckCount, schoolYear, semester, timeType);
        getSchoolYearListOption();
        dispatch({
            type: 'task/getQuestionCategoryList',
            payload: {},
        });
        dispatch({
            type: 'task/getDataSource',
            payload: {
                keyword: '',
                reqPageInfo: {
                    pageNumber: 1,
                    pageSize: 10,
                },
            },
        });
    }, []);
    const [form] = Form.useForm();

    const [columns, setColumns] = useState([
        {
            title: '编号',
            dataIndex: 'evaluateObjectNo',
            align: 'left',
            width: 80,
        },
        {
            title: '评定对象姓名',
            dataIndex: 'teacherUserName',
            align: 'left',
            width: 100,
            render: teacherUserName => (
                <Tooltip placement="topLeft" title={teacherUserName}>
                    {teacherUserName}
                </Tooltip>
            ),
        },
        {
            title: '课程',
            dataIndex: 'course',
            align: 'left',
            width: 60,
            render: course => (
                <Tooltip placement="topLeft" title={course}>
                    {course}
                </Tooltip>
            ),
        },
        {
            title: '学年',
            dataIndex: 'schoolYear',
            align: 'left',
            width: 60,
            render: schoolYear => (
                <Tooltip placement="topLeft" title={schoolYear}>
                    {schoolYear}
                </Tooltip>
            ),
        },
        {
            title: '学期',
            dataIndex: 'semester',
            align: 'left',
            width: 60,
            render: semester => (
                <Tooltip placement="topLeft" title={semester}>
                    {semester}
                </Tooltip>
            ),
        },
        {
            title: '问卷编号',
            dataIndex: 'evaluateExamNo',
            align: 'left',
            width: 60,
            render: evaluateExamNo => (
                <Tooltip placement="topLeft" title={evaluateExamNo}>
                    {evaluateExamNo}
                </Tooltip>
            ),
        },
        {
            title: '任务对象',
            dataIndex: 'evaluateTaskOf',
            align: 'left',
            width: 100,
            render: evaluateTaskOf => (
                <Tooltip placement="topLeft" title={evaluateTaskOf}>
                    {evaluateTaskOf}
                </Tooltip>
            ),
        },
        {
            title: '开放时间',
            align: 'left',
            width: 100,
            render: item => (
                <Tooltip placement="topLeft"
                         title={`${moment(item.evaluateTaskStartTime).format('YYYY-MM-DD hh:mm:ss')} - ${moment(item.evaluateTaskEndTime).format('YYYY-MM-DD hh:mm:ss')}`}>
                    {moment(item.evaluateTaskStartTime).format('YYYY-MM-DD hh:mm:ss')} - {moment(item.evaluateTaskEndTime).format('YYYY-MM-DD hh:mm:ss')}
                </Tooltip>
            ),
        },
        {
            title: '任务状态',
            dataIndex: 'evaluateTaskStatus',
            align: 'left',
            width: 100,
        },
        {
            title: '完成人数',
            align: 'left',
            width: 80,
            render: (item) => {
                return (
                    <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                            onClick={() => lookFinishSampleCount('已完成', item.evaluateTaskId)}>{item.finishSampleCount}</Button>
                );
            },
        },
        {
            title: '未完成人数',
            align: 'left',
            width: 80,
            render: (item) => {
                return (
                    <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                            onClick={() => lookFinishSampleCount('待完成', item.evaluateTaskId)}>{item.notFinishSampleCount}</Button>
                );
            },
        },
        isAdmin ? (
            {
                title: '操作',
                align: 'left',
                width: 80,
                render: (item) => {
                    return (
                        <div>
                            <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                                    onClick={() => updateItem(item)}>修改</Button>
                            <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                                    onClick={() => resetTask(item)}>重评</Button>
                            <Popconfirm title="是否要取消？" onConfirm={() => {
                                cancelEvaluateTask({ evaluateTaskId: item.evaluateTaskId }).then(res => {
                                    if (res.status === 'success') {
                                        dispatch({
                                            type: 'task/getDataSource',
                                            payload: {
                                                keyword: '',
                                                reqPageInfo: {
                                                    pageNumber: 1,
                                                    pageSize: 10,
                                                },
                                            },
                                        });
                                    } else {
                                        message.error(res.message);
                                    }
                                });
                            }}>
                                <Button style={{ padding: 2, fontWeight: 'bold', color: '#C21217' }}
                                        type="link">取消</Button>
                            </Popconfirm>
                            <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                                    onClick={() => {
                                        setAddModal(true);
                                        setItemId(item.evaluateTaskId);
                                        dispatch({
                                            type: 'task/getExpertTeacherListOption',
                                            payload: {},
                                        });
                                    }}>增加专家</Button>
                            <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                                    onClick={() => downLoad(item)}>导出</Button>
                        </div>
                    );
                },
            }
        ) : {},
    ]);

    const lookFinishSampleCount = (finishStatus, evaluateTaskId) => {
        dispatch({
            type: 'task/setFinishSampleCountModalVisible',
            payload: true,
        });
        dispatch({
            type: 'task/setFinishStatus',
            payload: finishStatus,
        });
        dispatch({
            type: 'task/setEvaluateTaskId',
            payload: evaluateTaskId,
        });
        dispatch({
            type: 'task/getTaskUserInfoTableList',
            payload: {
                finishStatus,
                evaluateTaskId,
            },
        });

    };

    const handleResize = index => (e, { size }) => {
        setColumns(() => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return nextColumns;
        });
    };
    const resizeColumns = columns.map((col, index) => ({
        ...col,
        onHeaderCell: column => ({
            width: column.width,
            onResize: handleResize(index),
        }),
    }));
    const title = '新增评价任务';
    const addItem = (item = {}) => {

        dispatch({
            type: 'task/getExpertTeacherListOption',
            payload: {},
        });
        dispatch({
            type: 'task/getUnitsTreeData',
            payload: {},
        });
        dispatch({
            type: 'task/setModalTitle',
            payload: '新增评价任务',
        });
        dispatch({
            type: 'task/setModalVisible',
            payload: true,
        });
        dispatch({
            type: 'task/setItemData',
            payload: item,
        });
    };
    const updateItem = (item) => {
        dispatch({
            type: 'task/setModalTitle',
            payload: '修改评价任务',
        });
        dispatch({
            type: 'task/setModalVisible',
            payload: true,
        });
        dispatch({
            type: 'task/setItemData',
            payload: item,
        });
    };


    const resetTask = (item) => {
        setItemId(item.evaluateTaskId);
        setResetTaskModal(true);
    };


    const downLoad = async (item) => {
        const { evaluateTaskId } = item;
        const res = await exportTaskUserList({ evaluateTaskId });
        let blob = new Blob([res.file], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
        FileSaver.saveAs(blob, res.filename);
    };
    const searchByKeyWord = (keyword) => {
        dispatch({
            type: 'task/getDataSource',
            payload: {
                keyword,
                reqPageInfo: {
                    pageNumber: reqPageInfo.pageNumber,
                    pageSize: reqPageInfo.pageSize,
                },
            },
        });
    };
    const searchByPageNumber = (pageNumber) => {
        dispatch({
            type: 'task/getDataSource',
            payload: {
                keyword,
                reqPageInfo: {
                    pageNumber,
                    pageSize: reqPageInfo.pageSize,
                },
            },
        });
    };

    const rowSelection = {
        type: 'radio',
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
        },
    };
    return (
        <div className={styles.pageContainer}>
            {
                isAdmin ? (
                    <div className={styles.pageContainerHeader}>
                        <SectionTitle title={title}/>
                        <div className={styles.filterContainer}>
                            <Input
                                className={styles.formWrapper}
                                value={listenCheckCount}
                                onChange={(e) => setListenCheckCount(e.target.value)}
                                placeholder="听查课次数"
                            />
                            <Select
                                placeholder="学年"
                                value={schoolYear}
                                onChange={(value) => setSchoolYear(value)}
                                className={styles.formWrapper}
                            >
                                {
                                    schoolYearListOption.map(item => {
                                        return <Option key={item.id} value={item.schoolYear}>{item.schoolYear}</Option>;
                                    })
                                }
                            </Select>
                            <Select
                                placeholder="学期"
                                value={semester}
                                onChange={(value) => setSemester(value)}
                                className={styles.formWrapper}
                            >
                                <Option value="第一学期">第一学期</Option>
                                <Option value="第二学期">第二学期</Option>
                            </Select>
                            <Select
                                placeholder="时间周期"
                                value={timeType}
                                onChange={(value) => setTimeType(value)}
                                className={styles.formWrapper}
                            >
                                <Option value="周">周</Option>
                                <Option value="月">月</Option>
                            </Select>
                            <Button
                                className={styles.marginRight}
                                type="primary"
                                onClick={() => {
                                    fetchEvaluateObjectList(listenCheckCount, schoolYear, semester, timeType);
                                }}
                            >
                                查询
                            </Button>
                            <Button
                                onClick={() => {
                                    setListenCheckCount('');
                                    setSchoolYear('');
                                    setSemester('');
                                    setTimeType('');
                                    fetchEvaluateObjectList('', '', '', '');
                                }}
                            >
                                重置
                            </Button>
                        </div>
                        <div className={styles.tableContainer}>
                            <Table
                                rowSelection={rowSelection}
                                bordered={false} // 是否有边框
                                rowKey='evaluateObjectId' // 唯一key值
                                loading={evaluateObjectListLoading} // 加载动画
                                columns={
                                    [
                                        {
                                            title: '评定对象编号',
                                            dataIndex: 'evaluateObjectNo',
                                            align: 'left',
                                        },
                                        {
                                            title: '教员姓名',
                                            dataIndex: 'teacherRealName',
                                            align: 'left',
                                        },
                                        {
                                            title: '证件号',
                                            dataIndex: 'credentialsNo',
                                            align: 'left',
                                        },
                                        {
                                            title: '课程',
                                            dataIndex: 'course',
                                            align: 'left',
                                        },
                                        {
                                            title: '上课学时',
                                            dataIndex: 'actualClassHours',
                                            align: 'left',
                                        },
                                        {
                                            title: '学年',
                                            align: 'left',
                                            dataIndex: 'schoolYear',
                                        },
                                        {
                                            title: '学期',
                                            dataIndex: 'semester',
                                            align: 'left',
                                        },
                                    ]
                                } // 表头
                                dataSource={evaluateObjectList}
                                pagination={false}
                            />
                        </div>
                        <div style={{ padding: '5px 0', display: selectedRowKeys.length === 0 ? 'none' : 'block' }}>
                            <Button type="primary" style={{ marginRight: '5px' }} onClick={() => {
                                addItem();
                            }}>确定</Button>
                            <Button type="warn" onClick={() => {
                                setSelectedRowKeys([]);
                                setSelectedRows([]);
                            }}>重置选择</Button>
                        </div>
                    </div>
                ) : null
            }

            <div className={styles.pageContainerTable}>
                <SectionTitle title={'已有评价任务'}/>
                <FilterByKeyWord onSearch={keyword => searchByKeyWord(keyword)}
                                 onReset={keyword => searchByKeyWord(keyword)}/>
                <div className={styles.tableContainer}>
                    <Table
                        components={{
                            header: {
                                cell: ResizableTitle,
                            },
                        }}
                        bordered={true} // 是否有边框
                        rowKey='evaluateTaskId' // 唯一key值
                        loading={loading} // 加载动画
                        columns={resizeColumns} // 表头
                        dataSource={dataSource.contentList}
                        pagination={{
                            total: dataSource.totalElements,// 总记录数
                            defaultPageSize: 10, // 默认显示条数
                            showQuickJumper: true, // 快速跳转
                            showSizeChanger: true, // 一页展示数据条数
                            onChange: (pageNumber) => searchByPageNumber(pageNumber),
                            showTotal: () => {
                                return `共${dataSource.totalElements}条`;
                            },
                        }}
                    />
                </div>
            </div>
            <UserModal
                title={modalTitle}
                visible={modalVisible}
                selectedRowKeys={selectedRowKeys}
                selectedRows={selectedRows}
                schoolYearListOption={schoolYearListOption}
                cbClear={() => {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                }}
            />
            <FinishSampleCountModal
                finishSampleCountModalVisible={finishSampleCountModalVisible}
                finishSampleCountList={finishSampleCountList}
                finishStatus={finishStatus}
                evaluateTaskId={evaluateTaskId}
                cb={(value) => dispatch({
                    type: 'task/setFinishSampleCountModalVisible',
                    payload: value,
                })}
                dispatch={dispatch}
            />
            <Modal
                title="重评"
                visible={resetTaskModal}
                width="600px"
                onOk={() => {
                    form.validateFields().then(values => {
                        values.evaluateTaskId = itemId;
                        values.taskStartDate = moment(values.time[0]).valueOf();
                        values.taskEndDate = moment(values.time[1]).valueOf();
                        delete values.time;
                        createEvaluateTaskAgain(values).then(res => {
                            if (res.status === 'success') {
                                dispatch({
                                    type: 'task/getDataSource',
                                    payload: {
                                        keyword: '',
                                        reqPageInfo: {
                                            pageNumber: 1,
                                            pageSize: 10,
                                        },
                                    },
                                });
                                form.resetFields();
                                setResetTaskModal(false);
                            } else {
                                message.error(res.message);
                            }
                        });
                    });
                }}
                onCancel={() => {
                    form.resetFields();
                    setResetTaskModal(false);
                }}
            >
                <Form
                    {...layout}
                    layout="horizontal"
                    form={form}
                >
                    <Form.Item
                        name="time"
                        label="开放时间"
                        rules={[{ type: 'array', required: true, message: '必填' }]}
                    >
                        <RangePicker
                            style={{ width: '100%' }}
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                        />
                    </Form.Item>
                </Form>
            </Modal>
            <AddTeacherModal addModal={addModal} itemId={itemId} cb={() => {
                setAddModal(false);
                dispatch({
                    type: 'task/getDataSource',
                    payload: {
                        keyword: '',
                        reqPageInfo: {
                            pageNumber: 1,
                            pageSize: 10,
                        },
                    },
                });
            }}/>
        </div>
    );
};
export default connect(({ task, dispatch, loading }) => ({
    task,
    dispatch,
    loading: loading.effects['task/getDataSource'],
}))(Task);
